import re

from django.conf import settings
from django.contrib.auth.backends import ModelBackend
from django.db.models import Q

from users.models import User


# def get_user_by_account(account):
#     '''判断 account 是否是手机号, 返回 user 对象'''
#     try:
#         if re.match('^1[3-9]\d{9}$', account):
#             user = User.objects.get(mobile=account)
#         else:
#             user = User.objects.get(username=account)
#     except User.DoesNotExist:
#         return None
#     else:
#         return user
from utils.secret import SecretOauth


class UsernameMobileAuthBackend(ModelBackend):
    #自定义认证后端
    def authenticate(self, request, username=None, password=None, **kwargs):
        #查找用户
        try:
            user = User.objects.get(Q(username = username) | Q(mobile = username))
        except User.DoesNotExist as e:
            return None
        #校验密码
        if not user.check_password(password):
            return None

        return user


# 2.生成激活链接
def generate_verify_email_url(request):
    # 1.user_id email
    data_dict = {
        'user_id': request.user.id,
        'email': request.user.email
    }
    # 2.将参数加密
    dumps_data = SecretOauth().dumps(data_dict)

    # 3.拼接 完整的激活路由
    verify_url = settings.EMAIL_VERIFY_URL + dumps_data

    return verify_url


